package org.example.controller;

import lombok.RequiredArgsConstructor;
import org.example.entity.AjaxResult;
import org.example.entity.Token;
import org.example.entity.vo.LoginVO;
import org.example.security.UserDetailsImpl;
import org.example.service.impl.TokenService;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
public class LoginController {
    private final TokenService tokenService;
    private final AuthenticationManager authenticationManager;

  /*  @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginVO) {
        Token token = tokenService.createToken(loginVO);
        return AjaxResult.ok(token);
    }*/
/*    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginVO) {
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(loginVO.getLoginName(), loginVO.getPassword());
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.login(usernamePasswordToken);
            return AjaxResult.ok(subject.getSession().getId());
        } catch (UnknownAccountException ex) {
            return AjaxResult.err("用户不存在");
        } catch (AuthenticationException ex) {
            return AjaxResult.err("用户名或密码错误");
        }

    }*/

    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginVO loginVO) {
        System.out.println("login");
        System.out.println("login");
        System.out.println("login");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginVO.getLoginName(), loginVO.getPassword());
        // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        Token token = tokenService.createToken((UserDetailsImpl)authenticate.getPrincipal());
        return AjaxResult.ok(token);
    }

    @GetMapping("/logout")
    public AjaxResult logout(@RequestHeader String token) {
        tokenService.removeToken(token);
        return AjaxResult.ok();
    }
}
